#include "State_MainMenu.h"
#include "Headers.h"

MainMenuState::MainMenuState(sf::RenderWindow &windowIn, StateManager& stateManagerIn) : 
GameState(windowIn, stateManagerIn), arrowKeySelect(false), bgFilename("img/bg/mainMenuBG.png"),
	selection(NOTHING), changeTo(NOTHING), bgTexture(txtrMgr.get(bgFilename))
{
	bgSprite.setTexture(bgTexture);
}

MainMenuState::~MainMenuState()
{
	clog << "Destroying MainMenuState.\n";
}

void MainMenuState::init()
{
	m_buttons[0] = new Button("img/button/mainMenu/new.png", 100, 100);
	m_buttons[1] = new Button("img/button/mainMenu/exit.png", 100, 500);
}

void MainMenuState::exit()
{
	txtrMgr.remove(bgFilename);
	delete m_buttons[0];
	delete m_buttons[1];
}

void MainMenuState::pause()
{

}

void MainMenuState::resume()
{

}

void MainMenuState::getInput(sf::RenderWindow& window)
{
	sf::Event evt;
	if (window.pollEvent(evt))
	{
		switch (evt.type)
		{
		case sf::Event::Closed:
			window.close();
			break;
		case sf::Event::MouseMoved:
			if (m_buttons[0]->isHighlighted(sf::Mouse::getPosition(window)) ||
				m_buttons[0]->isHighlighted(sf::Mouse::getPosition(window)))
				arrowKeySelect = false;
			break;
		case sf::Event::MouseButtonPressed:
			if (m_buttons[0]->isClicked(sf::Mouse::getPosition(window)))
				clog << "New Game button clicked!\n";
			if (m_buttons[1]->isClicked(sf::Mouse::getPosition(window)))
				clog << "Exit button clicked!\n";
				window.close();
			break;
		case sf::Event::KeyPressed:
			if (!arrowKeySelect)
			{
				arrowKeySelect = true;
				selection = NEW_GAME;
			}
			else
			{
				switch(evt.key.code)
				{
				case sf::Keyboard::Up:
					selection--;
					break;
				case sf::Keyboard::Down:
					selection++;
					break;
				case sf::Keyboard::Z:
				case sf::Keyboard::Return:
					if (selection == NEW_GAME)
						changeTo = NEW_GAME;
					else if (selection == EXIT)
						changeTo = EXIT;
				default:
					break;
				}
			}
			break;
		default:
			break;
		}
	}
}

void MainMenuState::update(StateManager& stateManager)
{
	if (selection > EXIT)
		selection = NEW_GAME;
	else if (selection < NOTHING)
		selection = EXIT;
	switch (changeTo)
	{
	case NOTHING:
		break;
	case NEW_GAME:
	case EXIT:
		stateManager.quit();
		break;
	default:
		break;
	}
}

void MainMenuState::draw(sf::RenderWindow& window)
{
	window.draw(bgSprite);
	m_buttons[0]->draw(window);
	m_buttons[1]->draw(window);
}